package com.nys.cqhttp.message.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.message.factory.IMessageHandler;

import com.nys.cqhttp.model.Massage;
import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.util.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * DirectUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 服务器
 * @date 2021/12/28 19:53
 */
public class FWQMessageHandler implements IMessageHandler {

  @Override
  public List<String> listHandler(Massage messagePojo, Context context) {
    return Arrays.asList(handler(messagePojo, context));
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    RestTemplate restTemplate = SpringContextUtil.getBean("restTemplate");
    try {
      JSONObject jsonObject =
          JSONObject.parseObject(
              restTemplate.getForEntity(messagePojo.getValue(), String.class).getBody());

      List<String> data = jsonObject.getObject("data", List.class);
      String res ="";
      for (int i = 0; i < data.size(); i++) {
        String datum = data.get(i);
        res += datum.substring(0, datum.length()-2);
        if (i+1 < data.size()){
          res +="\n";
        }
      }
      return StringUtils.isEmpty(res)
          ? "无玩家"
          : res;
    } catch (Exception e) {
      return null;
    }
  }
}
